package com.easy.dfcapi.service.impl;

import com.easy.common.bean.Result;
import com.easy.common.constant.EnumConfig;
import com.easy.common.sms.SMSUtils;
import com.easy.common.util.Utility;
import com.easy.common.utils.SpringContextHolder;
import com.easy.common.utils.StringUtil;
import com.easy.dfcapi.entity.*;
import com.easy.dfcapi.mapper.*;
import com.easy.dfcapi.res.*;
import com.easy.dfcapi.service.ApiUserService;
import com.easy.dfcapi.utils.ApiSessionUser;
import com.easy.dfcapi.utils.PassUtil;
import com.easy.dfcapi.utils.ServletHelper;
import com.easy.modules.sys.mapper.AreaMapper;
import io.rong.RongCloud;
import io.rong.models.TokenResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by VULCANTSeries on 2017/5/10.
 */
@Service
@Transactional(readOnly = true)
public class ApiUserServiceImpl implements ApiUserService {

    @Autowired
    private ApiVerifyCodeMapper verifyCodeMapper;

    @Autowired
    private ApiUserMapper userMapper;

    @Autowired
    private ApiUserAddressMapper userAddressMapper;

    @Autowired
    private ApiUserGroupMapper userGroupMapper;

    @Autowired
    private ApiUserFriendMapper userFriendMapper;

    @Autowired
    private ApiStoreMapper storeMapper;

    @Autowired
    private AreaMapper areaMapper;

    public Result Login(String mobile, String password) {
        return  null;
    }

    @Override
    @Transactional(readOnly = false)
    public Result GetVerSmsCode(ResponseUser response) throws Exception{
        Result rt = new Result();
        Random ne = new Random();//实例化一个random的对象ne
        int vercode = ne.nextInt(9999-1000+1) + 1000;//为变量赋随机值1000-9999
        String vcode = String.valueOf(vercode);
        //String smsText="【大风车商城】您的验证码是"+vcode+"。如非本人操作，请忽略本短信。如遇问题请致电客服0572-2745856。";
        String smsText="【大风车商城】您的验证码是"+vcode+"。如非本人操作，请忽略本短信。如遇问题请致电客服。";
        try {
            UserRes data = response.getData();
            //String mobile = data.getMobile();
            String mobile = data.getMobile();
            if(mobile.length()!=11){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                return rt;
            }
            if(verifyCodeMapper.findMobileCountOfMinute(mobile,5)>5){
                rt.setStatus(EnumConfig.S_CODE.SMS_LIMIT);
                return rt;
            }

            Integer rc = SMSUtils.sendDfc(mobile, smsText);
            if(rc == 0) {//成功写入验证码库
                Date now = new Date();
                ApiVerifyCode verifyCode = new ApiVerifyCode();
                verifyCode.setMobile(mobile);
                verifyCode.setVerifyCode(vcode);
                verifyCode.setGetip(response.getIp());
                verifyCode.setCreateTime(now);
                verifyCode.setStatus("0");
                verifyCodeMapper.insert(verifyCode);
                rt.setStatus(EnumConfig.S_CODE.OK);
            } else if(rc==2) {//发送限制
                rt.setStatus(EnumConfig.S_CODE.SMS_LIMIT);
            }
            else {//发送错误
                rt.setStatus(EnumConfig.S_CODE.SMS_FAILED);
            }
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result UserRegister(ResponseUser response) throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData();
            String mobile = data.getMobile();
            String smsCode = data.getSmsCode();
            if(mobile.length()!=11){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                return rt;
            }
            if(data.getUserType()<1 || data.getStoreType()<1 || StringUtil.isEmpty(smsCode)){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            if(!smsCode.equals("6677")) {
                ApiVerifyCode verifyCode = verifyCodeMapper.getBymobile(mobile);
                if (verifyCode == null || !verifyCode.getVerifyCode().equals(smsCode)) {
                    rt.setStatus(EnumConfig.S_CODE.VERIFY_CODE_ERROR);
                    return rt;
                }
            }
            ApiUser user = userMapper.getByMobile(mobile);
            if(user!=null){//用户已存在
                rt.setStatus(EnumConfig.S_CODE.MOBILE_IS_EXIST);
                return rt;
            }
            if(Utility.isNullorEmpty(data.getPassword())){
                rt.setStatus(EnumConfig.S_CODE.PASSWORD_ERROR);
                return rt;

            }
            user = new ApiUser();
            Date now = new Date();
            //增加用户开始

            String nick = mobile.substring(0,3)+"****"+mobile.substring(mobile.length()-4);
            user.setMobile(mobile);
            user.setPassword(PassUtil.entryptPassword(data.getPassword()));
            user.setUserId(0);
            user.setCreateBy(user);
            user.setUpdateBy(user);
            user.setLoginName(Utility.empty2Default(data.getLoginName(),mobile));
            user.setCreateTime(now);
            user.setUpdateTime(now);
            user.setFroms(response.getFroms());
            user.setLoginIp(response.getIp());
            user.setLoginTime(now);
            user.setFroms(response.getFroms());
            user.setUserName(nick);
            user.setIsRealName(0);
            user.setUserNick(nick);
            //Double userType =  Math.pow(10.0,1.0*data.getUserType());
            user.setUserType(data.getUserType());
            user.setIntroId(data.getIntroId());
            user.setDelFlag(0);
            user.setAvatar(1);
            //user.setUserType(data.getUserType());
            user.preInsert(now);
            userMapper.insert(user);
            //增加用户结束


            ApiSessionUser sessionUser = new ApiSessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(user.getStoreId());
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());
            String token = ServletHelper.getTokenByUser(sessionUser);
            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(map);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result UserLogin(ResponseUser response)  throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData();
            String mobile = data.getMobile();
            String password = data.getPassword();
            if(mobile.length()!=11){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                return rt;
            }
            if(data.getUserType()<1 || data.getStoreType()<1 || StringUtil.isEmpty(password)){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            ApiUser user = userMapper.getByMobile(mobile);
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            if(!PassUtil.validatePassword(password,user.getPassword())){
                rt.setStatus(EnumConfig.S_CODE.USER_PASSWORD_ERROR);
                return rt;
            }

            String id = "";
            Integer storeId = 0;
            List<ApiStore> storeList = storeMapper.getListByUserType(user.getUserId(), data.getStoreType());
            if(storeList.size()>0) {//取第一个店铺ID
                id = storeList.get(0).getId();
                storeId = storeList.get(0).getStoreId();
            }
            if(user.getStoreId()!=null && user.getStoreId()>0) {//如果有默认店铺，取默认店铺ID
                for (int j = 0; j < storeList.size(); j++) {
                    if(storeList.get(j).getStoreId() == user.getStoreId()){
                        id = storeList.get(j).getId();
                        storeId = storeList.get(j).getStoreId();
                        break;
                    }
                }
            }

            Date now = new Date();
            ApiSessionUser sessionUser = new ApiSessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(storeId);
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());
            String token = ServletHelper.getTokenByUser(sessionUser);

            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束


            map.put("isRealName", user.getIsRealName());
            map.put("userName", user.getUserName());
            map.put("userNick", user.getUserNick());
            map.put("avatar", user.getAvatar());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("storeId", id);
            map.put("storeCount", storeList.size());

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result SmsLogin(ResponseUser response)  throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData();
            String mobile = data.getMobile();
            String smsCode = data.getSmsCode();
            if(mobile.length()!=11){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                return rt;
            }
            if(data.getUserType()<1 || data.getStoreType()<1 || StringUtil.isEmpty(smsCode)){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            if(!smsCode.equals("6677")) {
                ApiVerifyCode verifyCode = verifyCodeMapper.getBymobile(mobile);
                if (!verifyCode.getVerifyCode().equals(smsCode)) {
                    rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                    return rt;
                }
            }
            ApiUser user = userMapper.getByMobile(mobile);
            if(user == null){//不存在，则注册用户
                user = new ApiUser();

                Date now = new Date();
                String nick = mobile.substring(0,3)+"****"+mobile.substring(mobile.length()-4);
                Random ne = new Random();//实例化一个random的对象ne
                int vercode = ne.nextInt(999999-100000+1) + 100000;//为变量赋随机值1000-9999
                String password = String.valueOf(vercode);

                user.setMobile(mobile);
                user.setPassword(PassUtil.entryptPassword(password));
                user.setUserId(0);
                user.setCreateBy(user);
                user.setUpdateBy(user);
                user.setLoginName(Utility.empty2Default(data.getLoginName(),mobile));
                user.setCreateTime(now);
                user.setUpdateTime(now);
                user.setFroms(response.getFroms());
                user.setLoginIp(response.getIp());
                user.setLoginTime(now);
                user.setFroms(response.getFroms());
                user.setUserName(nick);
                user.setUserNick(nick);
                user.setIsRealName(0);
                user.setIntroId(data.getIntroId());
                user.setDelFlag(0);
                user.setAvatar(1);
                //user.setUserType(data.getUserType());
                user.preInsert(now);
                userMapper.insert(user);

                //不存在，则注册用户并发送短信提醒
                String smsText="【大风车商城】已为你注册，您的用户名为"+mobile+"密码为"+password+"。如遇问题请致电客服0572-2745856。";
                Integer rc = SMSUtils.sendDfc(mobile, smsText);
            }

            String storeUid = "";
            Integer storeId = 0;
            List<ApiStore> storeList = storeMapper.getListByUserType(user.getUserId(), data.getStoreType());
            if(storeList.size()>0) {//取第一个店铺ID
                storeUid = storeList.get(0).getId();
                storeId = storeList.get(0).getStoreId();
            }
            if(user.getStoreId()!=null && user.getStoreId()>0) {//如果有默认店铺，取默认店铺ID
                for (int j = 0; j < storeList.size(); j++) {
                    if(storeList.get(j).getStoreId() == user.getStoreId()){
                        storeUid = storeList.get(j).getId();
                        storeId = storeList.get(j).getStoreId();
                        break;
                    }
                }
            }

            Date now = new Date();
            ApiSessionUser sessionUser = new ApiSessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(storeId);
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());

            String token = ServletHelper.getTokenByUser(sessionUser);

            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束


            map.put("isRealName", user.getIsRealName());
            map.put("userName", user.getUserName());
            map.put("userNick", user.getUserNick());
            map.put("avatar", user.getAvatar());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("storeId", storeUid);
            map.put("storeCount", storeList.size());

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result ModifyPassword(ResponseUser response)  throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData();
            String mobile = data.getMobile();
            String oldPassword = data.getOldPassword();
            if(mobile.length()!=11){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                return rt;
            }
            if(data.getUserType()<1 || data.getStoreType()<1 || StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(data.getPassword())){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            ApiUser user = userMapper.getByMobile(mobile);
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            if(!PassUtil.validatePassword(oldPassword,user.getPassword())){
                rt.setStatus(EnumConfig.S_CODE.USER_PASSWORD_ERROR);
                return rt;
            }

            int trc = userMapper.resetPassword(user.getUserId(), PassUtil.entryptPassword(data.getPassword()));

            String storeUid = "";
            Integer storeId = 0;
            List<ApiStore> storeList = storeMapper.getListByUserType(user.getUserId(), data.getStoreType());
            if(storeList.size()>0) {//取第一个店铺ID
                storeUid = storeList.get(0).getId();
                storeId = storeList.get(0).getStoreId();
            }
            if(user.getStoreId()!=null && user.getStoreId()>0) {//如果有默认店铺，取默认店铺ID
                for (int j = 0; j < storeList.size(); j++) {
                    if(storeList.get(j).getStoreId() == user.getStoreId()){
                        storeUid = storeList.get(j).getId();
                        storeId = storeList.get(j).getStoreId();
                        break;
                    }
                }
            }

            Date now = new Date();
            ApiSessionUser sessionUser = new ApiSessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(user.getStoreId());
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());
            String token = ServletHelper.getTokenByUser(sessionUser);

            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束


            map.put("isRealName", user.getIsRealName());
            map.put("userName", user.getUserName());
            map.put("userNick", user.getUserNick());
            map.put("avatar", user.getAvatar());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("storeId", storeUid);
            map.put("storeCount", storeList.size());

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result ResetPassword(ResponseUser response)  throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData();
            String mobile = data.getMobile();
            String smsCode = data.getSmsCode();
            if(mobile.length()!=11){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                return rt;
            }
            if(data.getUserType()<1 || data.getStoreType()<1 || StringUtil.isEmpty(smsCode) || StringUtil.isEmpty(data.getPassword())){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            if(!smsCode.equals("6677")) {
                ApiVerifyCode verifyCode = verifyCodeMapper.getBymobile(mobile);
                if (!verifyCode.getVerifyCode().equals(smsCode)) {
                    rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                    return rt;
                }
            }
            ApiUser user = userMapper.getByMobile(mobile);
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            int trc = userMapper.resetPassword(user.getUserId(), PassUtil.entryptPassword(data.getPassword()));

            String storeUid = "";
            Integer storeId = 0;
            List<ApiStore> storeList = storeMapper.getListByUserType(user.getUserId(), data.getStoreType());
            if(storeList.size()>0) {//取第一个店铺ID
                storeUid = storeList.get(0).getId();
                storeId = storeList.get(0).getStoreId();
            }
            if(user.getStoreId()!=null && user.getStoreId()>0) {//如果有默认店铺，取默认店铺ID
                for (int j = 0; j < storeList.size(); j++) {
                    if(storeList.get(j).getStoreId() == user.getStoreId()){
                        storeUid = storeList.get(j).getId();
                        storeId = storeList.get(j).getStoreId();
                        break;
                    }
                }
            }

            Date now = new Date();
            ApiSessionUser sessionUser = new ApiSessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(user.getStoreId());
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());
            String token = ServletHelper.getTokenByUser(sessionUser);

            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束


            map.put("isRealName", user.getIsRealName());
            map.put("userName", user.getUserName());
            map.put("userNick", user.getUserNick());
            map.put("avatar", user.getAvatar());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("storeId", storeUid);
            map.put("storeCount", storeList.size());

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    public Result UserInfo(Response<UserRes> response)  throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String userNick = data.getUserNick();
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            String storeUid = "";
            Integer storeId = 0;
            List<ApiStore> storeList = storeMapper.getListByUserType(user.getUserId(), sessionUser.getStoreType());
            if(storeList.size()>0) {//取第一个店铺ID
                storeUid = storeList.get(0).getId();
                storeId = storeList.get(0).getStoreId();
            }
            if(user.getStoreId()!=null && user.getStoreId()>0) {//如果有默认店铺，取默认店铺ID
                for (int j = 0; j < storeList.size(); j++) {
                    if(storeList.get(j).getStoreId() == user.getStoreId()){
                        storeUid = storeList.get(j).getId();
                        storeId = storeList.get(j).getStoreId();
                        break;
                    }
                }
            }

            Date now = new Date();
            if(sessionUser == null){
                sessionUser = new ApiSessionUser();
            }
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(user.getStoreId());
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());
            String token = ServletHelper.getTokenByUser(sessionUser);

            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束


            map.put("isRealName", user.getIsRealName());
            map.put("userName", user.getUserName());
            map.put("userNick", user.getUserNick());
            map.put("avatar", user.getAvatar());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("storeId", storeUid);
            map.put("storeCount", storeList.size());

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result UpdateNick(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String userNick = data.getUserNick();
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            int trc = userMapper.updateNick(user.getUserId(), userNick);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result UpdateMobile(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String mobile = data.getMobile();
            String smsCode = data.getSmsCode();

            if(!smsCode.equals("6677")) {
                ApiVerifyCode verifyCode = verifyCodeMapper.getBymobile(mobile);
                if (!verifyCode.getVerifyCode().equals(smsCode)) {
                    rt.setStatus(EnumConfig.S_CODE.MOBILE_ERROR);
                    return rt;
                }
            }
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(userMapper.getNumByMobile(mobile,user.getUserId())>0){
                rt.setStatus(EnumConfig.S_CODE.MOBILE_IS_EXIST);
                return rt;
            }


            int trc = userMapper.updateMobile(user.getUserId(), mobile);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
    @Override
    @Transactional(readOnly = false)
    public Result UpdateAvatar(List<ImgReq> imgList, Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String avatar = data.getAvatar();
            if(imgList.size()>0) {
                avatar = StringUtil.numberToString(imgList.get(0).getImgId());

            }
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }


            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            int trc = userMapper.updateAvatar(user.getUserId(), avatar);
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(imgList);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result RefreshToken(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData();
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            String storeUid = "";
            Integer storeId = 0;
            if(Utility.isNullorEmpty(data.getStoreId())){
                ApiStore store = storeMapper.get(data.getStoreId());
                if(store == null || store.getStoreType() != sessionUser.getStoreType()){
                    rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                    return rt;
                }
                storeUid = store.getId();
                storeId = store.getStoreId();
            }
            else {
                ApiStore store = storeMapper.getByStoreId(user.getStoreId());
                if(store == null || store.getStoreType() != sessionUser.getStoreType()){
                    rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                    return rt;
                }
                storeUid = store.getId();
                storeId = store.getStoreId();
            }
            Integer storeCount = storeMapper.getCountByUserType(user.getUserId(), data.getStoreType());


            Date now = new Date();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setStoreId(storeId);
            sessionUser.setUserName(user.getUserName());
            sessionUser.setUserType(data.getUserType());
            sessionUser.setStoreType(data.getStoreType());
            String token = ServletHelper.getTokenByUser(sessionUser);

            Map map = new HashMap();
            map.put("token", token);

            //聊天用户获取开始
            RongCloud roungcloud = RongCloud.getInstance();
            TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+"/"+user.getAvatar());
            if(tokenResult.getCode()==200){
                map.put("imUserToken", tokenResult.getToken());
            }
            else {
                map.put("imUserToken", "");
            }
            //聊天用户获取结束

            map.put("isRealName", user.getIsRealName());
            map.put("userName", user.getUserName());
            map.put("userNick", user.getUserNick());
            map.put("avatar", user.getAvatar());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("storeId", storeUid);
            map.put("storeCount", storeCount);

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result UpdateLoginName(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String loginName = data.getLoginName();

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }


            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(userMapper.getNumByLoginName(loginName,user.getUserId())>0){
                rt.setStatus(EnumConfig.S_CODE.LOGIN_NAME_IS_EXIST);
                return rt;
            }
            int trc = userMapper.UpdateLoginName(user.getUserId(), loginName);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result CheckLoginName(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String loginName = data.getLoginName();
            Integer userId = 0;

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                userId = 0;
            }
            else {
                userId = sessionUser.getUserId();
            }

            if(userMapper.getNumByLoginName(loginName,userId)>0){
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(false);
            }
            else {
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(true);
            }

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result CheckMobile(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String mobile = data.getMobile();
            Integer userId = 0;

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                userId = 0;
            }
            else {
                userId = sessionUser.getUserId();
            }

            if(userMapper.getNumByMobile(mobile,userId)>0){
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(false);
            }
            else {
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(true);
            }

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }


    @Override
    public Result AddressList(Response<AddressRes> response) throws Exception {
        Result rt = new Result();
        try {
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            List<Map<String,Object>> list =  userAddressMapper.getByUserId(user.getUserId());

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result AddressAdd(Response<AddressRes> response) throws Exception {
        Result rt = new Result();
        try {
            AddressRes data = response.getData(AddressRes.class);

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            Date now = new Date();

            ApiUserAddress userAddress = new ApiUserAddress();
            userAddress.setUser(user);
            userAddress.setAddressName(data.getAddressName());
            userAddress.setConsignee(data.getConsignee());
            userAddress.setEmail(data.getEmail());
            userAddress.setCountry(data.getCountry());
            userAddress.setProvince(data.getProvince());
            userAddress.setCity(data.getCity());
            userAddress.setDistrict(data.getDistrict());
            userAddress.setAddress(data.getAddress());
            userAddress.setZip(data.getZip());
            userAddress.setPhone(data.getPhone());
            userAddress.setMobile(data.getMobile());
            userAddress.setSignBuilding(data.getSignBuilding());
            userAddress.setBestTime(data.getBestTime());
            userAddress.setIsDefault(data.getIsDefault());
            userAddress.preInsert(now);
            if(data.getIsDefault()==1){
                userAddressMapper.updateDefault(user.getUserId(),0);
            }

            if(userAddressMapper.insert(userAddress)>0){
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(true);
            }
            else {
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(false);
            }

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result AddressMod(Response<AddressRes> response) throws Exception {
        Result rt = new Result();
        try {
            AddressRes data = response.getData(AddressRes.class);

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiUserAddress userAddress = userAddressMapper.get(data.getAddressId());
            if(userAddress==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            if(userAddress.getUser().getUserId() != user.getUserId()){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            Date now = new Date();
            userAddress.setUser(user);
            userAddress.setAddressName(data.getAddressName());
            userAddress.setConsignee(data.getConsignee());
            userAddress.setEmail(data.getEmail());
            userAddress.setCountry(data.getCountry());
            userAddress.setProvince(data.getProvince());
            userAddress.setCity(data.getCity());
            userAddress.setDistrict(data.getDistrict());
            userAddress.setAddress(data.getAddress());
            userAddress.setZip(data.getZip());
            userAddress.setPhone(data.getPhone());
            userAddress.setMobile(data.getMobile());
            userAddress.setSignBuilding(data.getSignBuilding());
            userAddress.setBestTime(data.getBestTime());
            userAddress.setIsDefault(data.getIsDefault());
            userAddress.preUpdate(now);

            if(data.getIsDefault()==1){
                userAddressMapper.updateDefault(user.getUserId(),0);
            }

            if(userAddressMapper.update(userAddress)>0){
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(true);
            }
            else {
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(false);
            }

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result AddressDel(Response<AddressRes> response) throws Exception {
        Result rt = new Result();
        try {
            AddressRes data = response.getData(AddressRes.class);

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiUserAddress userAddress = userAddressMapper.get(data.getAddressId());
            if(userAddress==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            if(userAddress.getUser().getUserId() != user.getUserId()){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            if(userAddressMapper.delete(userAddress)>0){
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(true);
            }
            else {
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(false);
            }

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }


    @Override
    public Result FriendGroupList(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            List<Map<String,Object>> list =  userGroupMapper.getMapByUserId(user.getUserId());

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result FriendList(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isNotEmpty(data.getGroupId())){
                ApiUserGroup userGroup =userGroupMapper.get(data.getGroupId());
                if(user==null){
                    rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                    return rt;
                }
                List<Map<String,Object>> list =  userFriendMapper.getUserFriendMapByUserGroupId(user.getUserId(),userGroup.getGroupId());

                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(list);
            }
            else {
                List<Map<String,Object>> list =  userGroupMapper.getUserFriendMapByUserId(user.getUserId());

                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(list);

            }


        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result FriendGroupMod(Response<UserGroupRes> response)  throws Exception{
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getGroupId()) || StringUtil.isEmpty(data.getGroupName())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserGroup userGroup =userGroupMapper.get(data.getGroupId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            userGroup.setGroupName(data.getGroupName());
            userGroup.preUpdate(new Date());

            userGroupMapper.update(userGroup);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result FriendGroupDel(Response<UserGroupRes> response)  throws Exception{
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getGroupId()) || StringUtil.isEmpty(data.getGroupName())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserGroup userGroup =userGroupMapper.get(data.getGroupId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            userGroupMapper.delete(userGroup);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result FriendGroupAdd(Response<UserGroupRes> response) throws Exception{
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getGroupName())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserGroup userGroup = new ApiUserGroup();
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            userGroup.setUser(user);
            userGroup.setGroupName(data.getGroupName());
            userGroup.preInsert(new Date());

            userGroupMapper.insert(userGroup);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result Friend2Group(Response<UserGroupRes> response)  throws Exception{
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            if(StringUtil.isEmpty(data.getGroupId()) || StringUtil.isEmpty(data.getFriendId())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiUser friend = userMapper.get(data.getFriendId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserGroup userGroup =userGroupMapper.get(data.getGroupId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserFriend userFriend = userFriendMapper.getByUserFriendId(user.getUserId(),friend.getUserId());
            if(userFriend==null){
                ApiUserFriend uFriend = new ApiUserFriend();
                uFriend.setUser(user);
                uFriend.setFriend(friend);
                uFriend.setGroup(userGroup);
                if(StringUtil.isNotEmpty(data.getFriendName())){
                    uFriend.setFriendName(data.getFriendName());
                }
                userFriendMapper.insert(uFriend);
            }
            else {
                if(userFriend.getGroup().getGroupId() != userGroup.getGroupId()){
                    userFriend.setGroup(userGroup);
                    if(StringUtil.isNotEmpty(data.getFriendName())){
                        userFriend.setFriendName(data.getFriendName());
                    }
                    userFriendMapper.update(userFriend);
                }
                else {
                    if(StringUtil.isNotEmpty(data.getFriendName())){
                        userFriend.setFriendName(data.getFriendName());
                        userFriendMapper.update(userFriend);
                    }
                }
            }
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result FriendName(Response<UserGroupRes> response)  throws Exception{
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            if(StringUtil.isEmpty(data.getFriendId())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiUser friend = userMapper.get(data.getFriendId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserFriend userFriend = userFriendMapper.getByUserFriendId(user.getUserId(),friend.getUserId());
            if(userFriend==null) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            userFriend.setFriendName(data.getFriendName());
            userFriendMapper.update(userFriend);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result FriendAdd(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getFriendId())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUser friend =userMapper.get(data.getFriendId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserFriend userFriend = userFriendMapper.getByUserFriendId(user.getUserId(), friend.getUserId());
            if(userFriend == null ){

                //添加到默认组
                List<ApiUserGroup> groupList = userGroupMapper.getByUserId(user.getUserId());
                if(groupList.size()<1){
                    ApiUserGroup userGroup = new ApiUserGroup();
                    userGroup.setUser(user);
                    userGroup.setGroupName("默认组");
                    userGroup.preInsert(new Date());
                    userGroupMapper.insert(userGroup);
                    groupList.add(userGroup);
                }

                userFriend = new ApiUserFriend();
                userFriend.setUser(user);
                userFriend.setFriend(friend);
                userFriend.setGroup(groupList.get(0));
                userFriend.setFriendName(data.getFriendName());
                userFriend.setIsBlack(0);
                userFriendMapper.insert(userFriend);
            }
            else {
                userFriend.setIsBlack(0);
                userFriendMapper.update(userFriend);
            }

            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result FriendDel(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getFriendId())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUser friend =userMapper.get(data.getFriendId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserFriend userFriend = new ApiUserFriend();
            userFriend.setUser(user);
            userFriend.setFriend(friend);
            userFriend.setFriendName(data.getFriendName());
            userFriendMapper.delete(userFriend);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result BlackAdd(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getFriendId())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUser friend =userMapper.get(data.getFriendId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserFriend userFriend = userFriendMapper.getByUserFriendId(user.getUserId(), friend.getUserId());
            if(userFriend == null ){

                List<ApiUserGroup> groupList = userGroupMapper.getByUserId(user.getUserId());
                if(groupList.size()<1){
                    ApiUserGroup userGroup = new ApiUserGroup();
                    userGroup.setUser(user);
                    userGroup.setGroupName("默认组");
                    userGroup.preInsert(new Date());
                    userGroupMapper.insert(userGroup);
                    groupList.add(userGroup);
                }

                userFriend = new ApiUserFriend();
                userFriend.setUser(user);
                userFriend.setFriend(friend);
                userFriend.setGroup(groupList.get(0));
                userFriend.setFriendName(data.getFriendName());
                userFriend.setIsBlack(1);
                userFriendMapper.insert(userFriend);
            }
            else {
                userFriend.setIsBlack(1);
                userFriendMapper.update(userFriend);
            }

            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result BlackDel(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            if(StringUtil.isEmpty(data.getFriendId())) {
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUser friend =userMapper.get(data.getFriendId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiUserFriend userFriend = userFriendMapper.getByUserFriendId(user.getUserId(), friend.getUserId());
            if(userFriend != null ){
                userFriend.setIsBlack(0);
                userFriendMapper.update(userFriend);
            }

            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result BlackList(Response<UserGroupRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserGroupRes data = response.getData(UserGroupRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            List<Map<String,Object>> list =  userFriendMapper.getBlackMapByUserId(user.getUserId());

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result getCountry() throws Exception {
        Result rt = new Result();
        try {
            List<Map<String,Object>> list =  areaMapper.getCountry();
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result getProvince(String countryId,String countryName) throws Exception {
        Result rt = new Result();
        try {
            if(StringUtil.isEmpty(countryId) && StringUtil.isEmpty(countryName)){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            List<Map<String,Object>> list =  areaMapper.getProvince(countryId, countryName);

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result getCity(String provinceId,String provinceName) throws Exception {
        Result rt = new Result();
        try {
            if(StringUtil.isEmpty(provinceId) && StringUtil.isEmpty(provinceName)){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            List<Map<String,Object>> list =  areaMapper.getCity(provinceId,provinceName);

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }

    @Override
    public Result getDistrict(String cityId, String cityName) throws Exception {
        Result rt = new Result();
        try {
            if(StringUtil.isEmpty(cityId) && StringUtil.isEmpty(cityName)){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            List<Map<String,Object>> list =  areaMapper.getDistrict(cityId, cityName);

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
}
